import { BaseStrategy } from '../BaseStrategy.js';
import { delay, ensurePageOpen } from '../../utils.js';
import { platformConfig } from '../../config/index.js';
import { wuliu_rule } from '../../rules/wuliu.js';
import { closePopups } from '../../utils.js';
import path, { dirname, join } from 'path';
import { fileURLToPath } from 'url';
import { logInfo, logWarn, logError } from '../../logger.js';
import fs from 'fs';
import statisticsService from '../../services/statistics.js';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

export class WeixinStrategy extends BaseStrategy {
  constructor(context) {
    super(context, platformConfig.weixin);
  }

  async processRefunds(accountKey) {
    logInfo('[WeixinAutomation] 开始处理微信退款订单');
    let refundRecords = [];
    try {
      const page = await ensurePageOpen(this.context, this.baseUrl + '/shop/aftersale/home');
      this.pageLoad(page);
      logInfo('[WeixinAutomation] 浏览器已启动');
      await page.waitForLoadState('networkidle');
      await page.waitForTimeout(5000);
      await closePopups(page);
      await page.locator('div.tab').getByText('待收货').click({ time: 1000 }).catch(() => { logWarn('[WeixinAutomation] 未找到待收货按钮'); });
      await page.waitForTimeout(5000);
      let count = await page.locator('div.tab').getByText('待收货').textContent();
      //获取count 中的数字
      count = parseInt(count.match(/\d+/)[0]);
      logInfo(`[WeixinAutomation] 待收货订单数量: ${count}`);

      while (count > 0) {
        // 获取订单列表
        const hasnext = await this.processRefundItems(page, refundRecords);
        if (!hasnext) {
          break;
        }
        // 刷新列表
        await page.getByRole('button', { name: '查询' }).click({ timeout: 1000 }).catch(() => { logWarn('[WeixinAutomation] 点击查询失败'); });
        await page.waitForTimeout(5000);
        await page.locator('div.tab').getByText('待收货').click({ time: 1000 }).catch(() => { logWarn('[WeixinAutomation] 未找到待收货按钮'); });
        await page.waitForTimeout(5000);
      }
      // 保存所有退款成功数据
      if (accountKey && refundRecords.length > 0) {
        statisticsService.saveRefundRecord(accountKey, refundRecords);
      }
      logInfo('[WeixinAutomation] 退款任务执行完成');
    } catch (err) {
      logError(`[WeixinAutomation] 退款任务异常: ${err.stack || err}`);
    }
  }
  async processRefundItems(page, refundRecords = []) {
    logInfo('[WeixinAutomation] 开始处理退款订单列表');
    let refundCount = 0;
    const items = page.locator('div.weui-desktop-table__main .weui-desktop-table__core-table tbody tr');
    const count = await items.count();
    logInfo(`[WeixinAutomation] 订单数量：${count}`);
    for (let i = 0; i < count; i++) {
      const item = items.nth(i);
      // 获取退货类型
      const refundType = await item.locator('td:nth-child(3) div span:nth-child(1)').textContent();
      logInfo(`[WeixinAutomation] 退货类型：${refundType}`);

      if (!refundType.includes('退货退款')) {
        continue;
      }
      // 获取退货状态
      const refundStatus = await item.locator('div.express-wrp-refund').filter({ hasText: '退货' }).locator('div  span div span div span').textContent();
      logInfo(`[WeixinAutomation] 退货状态：${refundStatus}`);
      if (refundStatus !== '已签收') {
        continue;
      }

      const newPagePromise = this.context.waitForEvent('page');
      await item.getByRole('link', { name: '详情' }).click({ timeout: 1000 }).catch(() => { logWarn('[WeixinAutomation] 点击详情失败'); });
      const detailPage = await newPagePromise;
      const itemData = await this.processDetail(detailPage, item);
      if (itemData) {
        logInfo(`[WeixinAutomation] 追加数据：${JSON.stringify(itemData)}`);
        refundCount++;
        // 处理每个退款成功订单时，push 到 refundRecords
        refundRecords.push(itemData);
      }
    }
    return refundCount > 5;
  }
  async processDetail(detailPage, item) {
    logInfo('[WeixinAutomation] 进入订单详情页');
    await detailPage.waitForLoadState();
    await detailPage.waitForTimeout(3000);
    await closePopups(detailPage);
    const thbox = await detailPage.locator('div.el-card').filter({ hasText: '退货物流' });
    await thbox.getByText('更多物流信息').click({ timeout: 1000 }).catch(() => { logWarn('[WeixinAutomation] 点击更多物流信息失败'); });
    await detailPage.waitForTimeout(5000);
    // 获取物流信息
    const logistics_info = await thbox.locator('.logistics_info .item').allTextContents();
    const wuliulist = logistics_info.reverse();
    logInfo(`[WeixinAutomation] 物流信息：${wuliulist[0]}`);

    const result = await wuliu_rule(wuliulist);
    if (!result) {
      await detailPage.close();
      return false;
    }

    // 同意流程

    await detailPage.getByRole('button', { name: '收货并退款' }).click({ timeout: 1000 }).catch(() => { logWarn('[WeixinAutomation] 点击收货并退款失败'); });
    await detailPage.locator('.weui-desktop-popover').getByRole('button', { name: '同意退款', exact: true }).click({ timeout: 1000 });

    const itemInfo = {
      '订单编号': await detailPage.locator('div.item').filter({ hasText: '订单编号' }).locator('span')
        .first().textContent().catch(() => { }),
      '退款编号': await detailPage.locator('div.item').filter({ hasText: '售后单号' }).locator('span')
        .first().textContent().catch(() => { }),
      '售后时间': new Date().toLocaleString(),
    };
    await detailPage.close();
    return itemInfo;
  }

  async getShipmentInfo(shopName) {
    logInfo('[WeixinAutomation] 获取微信物流信息');
    // TODO: 实现微信物流信息获取
    return {
      '店铺名称': shopName || '微信',
      '物流信息': '暂未实现'
    };
  }

  async getExchangePendingCount() {
    logInfo('[WeixinAutomation] 获取微信换货待处理订单数');
    try {
      const page = await ensurePageOpen(this.context, this.baseUrl + '/shop/aftersale/home');
      this.pageLoad(page);
      logInfo('[WeixinAutomation] 浏览器已启动');
      await page.waitForLoadState('networkidle');
      await page.waitForTimeout(5000);
      await closePopups(page);
      const tabText = await page.locator('div.tab').getByText('换货待处理').textContent();
      //获取tabText 中的数字
      const count = parseInt(tabText.match(/\d+/)[0]);
      return count;
    } catch (error) {
      logError(`[WeixinAutomation] 获取微信换货待处理订单数异常: ${error.stack || error}`);
      return '获取失败';
    }
  }

  async test() {
    const page = await ensurePageOpen(this.context, this.baseUrl + '/shop/aftersale/home');
    this.pageLoad(page);
    await page.pause();
  }
}
